package com.webull.information.center.carwler.dao;

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.webull.framework.util.UtilJdbc;
import com.webull.information.center.carwler.common.model.CollectRecord;
import com.webull.information.center.carwler.common.model.parm.CollectParm;
import com.webull.information.center.dao.JdbcHelper;

/**
 * JOB采集状态记录
 *
 * @author shimingjun
 * @version 1.0
 * @date 2016年7月27日 下午6:46:33
 * @since JDK 1.8
 */
@Repository
public class CollectRecordDao {
	private static final RowMapper<CollectRecord> collectRcoordRM = BeanPropertyRowMapper
			.newInstance(CollectRecord.class);
	protected final Logger logger = LogManager.getLogger(getClass());

	private @Autowired JdbcTemplate jdbcTemplate;

	private @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public List<CollectRecord> search(CollectParm parm) {
		String sql = Sql.SEARCH_BY_PARM;
		if (parm != null && parm.getCollectJob() != null) {
			sql += " and collect_job = :collectJob ";
		}
		if (parm != null && parm.getExchangeId() != null) {
			sql += " and exchange_id = :exchangeId ";
		}
		if (parm != null && parm.getExchangeCode() != null) {
			sql += " and exchange_code = :exchangeCode ";
		}
		if (parm != null && parm.getLanguage() != null) {
			sql += " and language = :language ";
		}
		if (parm != null) {
			sql = sql + " and record_type=:recordType ";
		}
		sql += " order by collect_time desc";

		return namedParameterJdbcTemplate.query(sql, JdbcHelper.getSqlParameterSource(parm), collectRcoordRM);
	}

	public Integer add(CollectRecord record) {
		logger.info("sql={}, {}", Sql.ADD, record);
		return UtilJdbc.insertAndReturnIntKey(namedParameterJdbcTemplate, Sql.ADD, record);
	}

	private class Sql {
		private static final String SEARCH_BY_PARM = "select * from wli_collect_record where del = 0 ";
		private static final String ADD = "INSERT into wli_collect_record (last_ticker_id,exchange_id,exchange_code,record_type,collect_time,language,collect_job,customer) VALUEs	 (:lastTickerId, :exchangeId,:exchangeCode,:recordType,ifnull(:collectTime,now()),:language,:collectJob,:customer)";

	}

}
